package com.zb.util;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.util.List;

@Component
public class CanalUtil {

    @Autowired
    private RestTemplate restTemplate;

    public void main() {
        System.out.println("开启同步");
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
                11111), "example", "", "");
        int batchSize = 1000;
        try {
            //创建连接
            connector.connect();
            //监听mysql所有的库和表
            connector.subscribe(".*\\..*");
            //回滚到未进行ack的地方，下次fetch的时候，可以从最后一个没有ack的地方开始拿
            connector.rollback();
            boolean flag = true;
            while (flag) {
                Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                //用户没有更改数据库中的数据
                if (batchId == -1 || size == 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    //获取修改的每一条记录
                    printEntry(message.getEntries());
                }
                connector.ack(batchId); // 提交确认
            }
        } finally {
            connector.disconnect();
        }
    }


    private void printEntry(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            //检查到当前执行的代码是事物操作， 跳转下次
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }
            //代码固定，获取rowChage对象
            CanalEntry.RowChange rowChage = null;
            try {
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e);
            }
            //rowChage getEventType 获取事件类型对象
            CanalEntry.EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================> binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));
            //处理数据
            if (entry.getHeader().getSchemaName().equals("shop_content")
                    && entry.getHeader().getTableName().equals("tb_content")) {
                proccessShopContent(rowChage, eventType);
            }
        }
    }

    public void proccessShopContent(CanalEntry.RowChange rowChage, CanalEntry.EventType eventType) {
        for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
            if (eventType == CanalEntry.EventType.DELETE) {
                //rowData.getBeforeColumnsList()获取删除之前的数据
                printColumn(rowData.getBeforeColumnsList());
            } else if (eventType == CanalEntry.EventType.INSERT) {
                //rowData.getAfterColumnsList()获取添加之后的数据
                printColumn(rowData.getAfterColumnsList());
            } else {
                //获取修改之前的数据
                System.out.println("-------> before");
                printColumn(rowData.getBeforeColumnsList());
                //获取修改之后的数据
                System.out.println("-------> after");
                printColumn(rowData.getAfterColumnsList());
            }
        }
    }


    private void printColumn(List<CanalEntry.Column> columns) {
        String cid = "";
        for (CanalEntry.Column column : columns) {
            if (column.getName().equals("category_id")) {
                cid = column.getValue();
                break;
            }
            // System.out.println(column.getName() + " : " + column.getValue() + "  update=" + column.getUpdated());
        }
        String url = "http://localhost:9090/mysave?cid=" + cid;
        String result = restTemplate.getForObject(url, String.class);
        System.out.println(result);
    }
}
